import jieba
from flask import Flask, render_template, jsonify
from pandas._libs.internals import defaultdict
import utils


app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template("index.html")

@app.route('/time')
def get_time():
    return utils.get_time()

@app.route('/l1')
def set_ec_l1():
    l1_datas = utils.get_l1_data()
    ec_l1_x = []
    ec_l1_data = []
    for x,data in l1_datas:
        ec_l1_x.append(x)
        ec_l1_data.append(data)
    return jsonify({"l1_x":ec_l1_x,"l1_data":ec_l1_data})

@app.route('/l2')
def set_ec_l2():
    l2_datas = utils.get_l2_data()
    ec_l2_data = []
    for name,data in l2_datas:
        ec_l2_data.append({"name": name, "value": data})
    return jsonify({"l2_data":ec_l2_data})

@app.route('/r2')
def set_ec_r2():
    r2_datas = utils.get_r2_data()
    ec_r2_name = []
    ec_r2_data = []
    for name,data in r2_datas:
        ec_r2_name.append(name)
        ec_r2_data.append(data)
    return jsonify({"r2_name":ec_r2_name,"r2_data":ec_r2_data})

@app.route('/m1')
def set_ec_m1():
    m1_datas = utils.get_m1_data()
    temp_data = defaultdict(list)
    for x,data in m1_datas:
        temp_data[x].append(data)
    ec_m1_x = []
    ec_m1_data = []
    for k, v in temp_data.items():
        ec_m1_x.append(k)
        ec_m1_data.append(v)
    return jsonify({"m1_x":ec_m1_x,"m1_data":ec_m1_data})

@app.route('/m2')
def set_ec_m2():
    m2_datas = utils.get_m2_data()
    temp_data = defaultdict(list)
    for x,data in m2_datas:
        temp_data[x].append(data)
    ec_m2_x = []
    ec_m2_data = []
    for k, v in temp_data.items():
        ec_m2_x.append(k)
        ec_m2_data.append(v)
    return jsonify({"m2_x":ec_m2_x,"m2_data":ec_m2_data})

@app.route('/r1')
def set_ec_r1():
    r1_datas = utils.get_r1_data()
    ec_r1_x = []
    ec_r1_data = []
    for x,data in r1_datas:
        ec_r1_x.append(x)
        ec_r1_data.append(data)
    return jsonify({"r1_x":ec_r1_x,"r1_data":ec_r1_data})


@app.route('/m3')
def set_m3_data():
    data = str(utils.get_m3_data())
    d = []
    counts = {}
    words=jieba.lcut(data)
    for word in words:
        if len(word) == 1:
            continue
        elif word.isdigit():
            continue
        else:
            counts[word] = counts.get(word, 0) + 1
    items = list(counts.items())
    items.sort(key=lambda x: x[1], reverse=True)
    for x in range(500):
        word, count = items[x]
        d.append({"name": word, "value": count})
    return jsonify({"kws": d})

if __name__ == '__main__':
    app.run()
